package com.jxb.tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树-前序遍历
 * 逻辑：先访问根节点的值，然后再访问所有左子树，右子树
 */
public class BinTreePreOrderTraversal_144 {

    public static void main(String[] args) {

    }

    //递归
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        accessTree(root, res);
        return res;
    }

    public void accessTree(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        res.add(root.val);
        accessTree(root.left,res);
        accessTree(root.right,res);
    }

    //栈
    public List<Integer> inorderTraversalWithLoop(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                res.add(root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root =  root.right;
        }
        return res;
    }


}
